/**
 * Http 封装
 */

class HttpHelper {

    /**
     * get请求
     *
     * @param  {[type]}   url [description]
     * @param  {Function} cb  [description]
     * @return {[type]}       [description]
     */
    static get (url, cb) {
        let xhr = cc.loader.getXMLHttpRequest()

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let respone = xhr.responseText
                let rsp = JSON.parse(respone)

                cb(rsp)
            } else if (xhr.readyState === 4 && xhr.status !== 200) {
                cb( {status: xhr.status, code: 502, msg: '网络错误'} )
            }
        }

        xhr.open('GET', url, true)
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
        xhr.timeout = 10000

        xhr.send()
    }

    /**
     * post请求
     *
     * @param  {[type]}   url  [description]
     * @param  {[type]}   data [description]
     * @param  {Function} cb   [description]
     * @return {[type]}        [description]
     */
    static post (url, data, cb) {
        let xhr = cc.loader.getXMLHttpRequest()

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let respone = xhr.responseText
                let rsp = JSON.parse(respone)

                cb(rsp)
            } else if (xhr.readyState === 4 && xhr.status !== 200) {
                cb( {status: xhr.status, code: 502, msg: '网络错误'} )
            }
        }

        xhr.open('POST', url, true)
        // xhr.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded")
        xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8')
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
        xhr.timeout = 10000

        xhr.send(JSON.stringify(data))
    }
}

module.exports = HttpHelper
